package cn.zkc.library.controller;

import cn.zkc.library.biz.LoginBiz;
import cn.zkc.library.dao.UserDAO;
import cn.zkc.library.modal.User;
import cn.zkc.library.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private LoginBiz loginBiz;

    @RequestMapping(path = {"/users/login"}, method = {RequestMethod.GET})
    public String login() {
        return "login/login";
    }

    @RequestMapping(path = {"/user/login/do"}, method = {RequestMethod.POST})
    public String doLogin(
            Model model,
            @RequestParam("email") String email,
            @RequestParam("password") String password,
            HttpServletResponse response
    ) {
        try {
            String t = loginBiz.login(email, password);
            CookieUtils.writeCookie("t", t, response);
            return "redirect:/index";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "404";
        }

    }
}
